package com.ly.mpayment.rest.system;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import com.ly.mpayment.core.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ly.mpayment.persist.entity.DownShopInfo;
import com.ly.mpayment.persist.entity.User;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.downshoprechargeservice.IDownShopRechargeService;
import com.ly.mpayment.persist.service.user.IUserService;
import com.ly.mpayment.rest.AbsRest;

import net.sf.json.JSONObject;

@Component
@Path("system/downrecharge/")
public class DownRechargeRest extends AbsRest {

	@Autowired
	IUserService userService;

	@Autowired
	IDownShopInfoService shopService;

	@Autowired
	IDownShopRechargeService rechargeService;


	Logger logger = Logger.getLogger(DownRechargeRest.class);
	/**
	 * 下游充值
	 *
	 * @param data
	 * @param request
	 * @return
	 */
	@Path("downRecharge")
	@POST
	public String downRecharge(String data, @Context HttpServletRequest request) {
		String result = this.validationParameter(data, request, userService, "downshopuuid", "downshopbalance","recharge",
				"remark");
		if (result == null) {
			JSONObject json = JsonUtils.converToJson(data);
			// 检查操作用户是否是管理员操作，只有管理员才能操作
			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject userInfo = JsonUtils.converToJson(jwt.getSubject());
						if (userInfo != null) {
							User adminUser = userService.findByUserid(userInfo.getString(Config.tokenSignAttr));
							if (adminUser != null && UserUtil.checkRole(adminUser)) {
								DownShopInfo shop = shopService.findById(json.getString("downshopuuid"));
								if (shop != null) {
//									BigDecimal big = shop.getDownshopbalance();
									int payType = json.getInt("recharge") == 1 ? 1 : 2;
									if( payType == Config.RECHARGE[0]){
//										shop.setDownshopbalance(big.add(BigUtil.getBigDecimal(json.getString("downshopbalance"))));
										json.put("remark",json.getString("remark").equals("") ? Config.recharge[0] : json.getString("remark"));
									}else{
//										shop.setDownshopbalance(big.subtract(BigUtil.getBigDecimal(json.getString("downshopbalance"))));
										json.put("remark",json.getString("remark").equals("") ? Config.recharge[1] : json.getString("remark"));
									}
									if(this.shopService.updateDownShopInfo(null, shop, BigUtil.getBigDecimal(json.getString("downshopbalance")), json.getString("remark"),payType,adminUser)){
										return ResultMessage.getSucceed(null);
									}
//									if (this.shopService.updateShopAmount(shop, adminUser,BigUtil.getBigDecimal(json.getString("downshopbalance")),json.getString("remark"),payType)) {
//										return ResultMessage.getSucceed(null);
//									}
									return ResultMessage.getFailt("");
								}
								return ResultMessage.getFailt(ResultMessage.shopexistError);
							}
							return ResultMessage.getFailt(ResultMessage.notAuthority);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	@Path("findRechargeRecord")
	@POST
	public String findRechargeRecord(String data, @Context HttpServletRequest request) {
		String result = this.validationParameter(data, request, userService,"start", "pageSize", "starttime","endtime","useruuid");
		if (result == null) {
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			if (!StringUtils.isBlank(json.getString("starttime"))) {
				parameters.put(":starttime", json.getString("starttime"));
			}
			if (!StringUtils.isBlank(json.getString("endtime"))) {
				parameters.put(":endtime", json.getString("endtime"));
			}
			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject userInfo = JsonUtils.converToJson(jwt.getSubject());
						if (userInfo != null) {
							User adminUser = userService.findByUserid(userInfo.getString(Config.tokenSignAttr));
							if (adminUser != null && UserUtil.checkRoleDown(adminUser)) {
									parameters.put(":useruuid", adminUser.getUseruuid());
							}
							if(!StringUtils.isBlank(json.getString("useruuid"))){
								parameters.put(":useruuid", json.getString("useruuid"));
							}
							if(adminUser.getUsertype() == 3){
								return ResultMessage.getSucceed(
										JsonUtils.excludes(this.rechargeService.findPageDownShopRecharge(parameters, json.getInt("start"),
												json.getInt("pageSize")), new String[] { "platFormAccount","errorCodesForUseruuid","createtime","useruuid",
												"password","","wechatid","lastlogintime" ,"token","usertype" ,"userstatus","phonenum","remark" }));
							}else{
								return ResultMessage.getSucceed(
										JsonUtils.excludes(this.rechargeService.findPageDownShopRecharge(parameters, json.getInt("start"),
												json.getInt("pageSize")), new String[] { "platFormAccount","errorCodesForUseruuid","createtime","useruuid",
												"password","","wechatid","lastlogintime" ,"token","usertype" ,"userstatus","phonenum" }));
							}

						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	@Path("exportdataRechargeRecord")
	@POST
	public String exportdataRechargeRecord(String data, @Context HttpServletRequest request) {
		String result = this.validationParameter(data, request, userService,"start", "pageSize", "starttime","endtime","useruuid");
		if (result == null) {
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			if (!StringUtils.isBlank(json.getString("starttime"))) {
				parameters.put(":starttime", json.getString("starttime"));
			}
			if (!StringUtils.isBlank(json.getString("endtime"))) {
				parameters.put(":endtime", json.getString("endtime"));
			}
			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject userInfo = JsonUtils.converToJson(jwt.getSubject());
						if (userInfo != null) {
							User adminUser = userService.findByUserid(userInfo.getString(Config.tokenSignAttr));
							if (adminUser != null && UserUtil.checkRoleDown(adminUser)) {
								parameters.put(":useruuid", adminUser.getUseruuid());
							}
							if(!StringUtils.isBlank(json.getString("useruuid"))){
								parameters.put(":useruuid", json.getString("useruuid"));
							}
							JSONObject obj = JsonUtils.getJSONOBJCT();
							if(adminUser.getUsertype() == 3){

								String exportResult = ExportExcelUtil.exportdataRechargeRecord(this.rechargeService.findPageDownShopRecharge(parameters,0,1000000));
								logger.info("exportResult:"+exportResult);
								if(exportResult != null){
									obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
									return ResultMessage.getSucceed(obj.toString());
								}else{
									return ResultMessage.getFailt("");
								}
							}else{
								String exportResult = ExportExcelUtil.exportdataRechargeRecord(this.rechargeService.findPageDownShopRecharge(parameters,0,1000000));
								logger.info("exportResult:"+exportResult);
								if(exportResult != null){
									obj.put("path",CookieRedis.get("download").concat(File.separator) + exportResult.replace(CookieRedis.get("exportPath"), ""));
									return ResultMessage.getSucceed(obj.toString());
								}else{
									return ResultMessage.getFailt("");
								}
							}

						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	@Path("downRechargeRecordCount")
	@POST
	public String downRechargeRecordCount(String data, @Context HttpServletRequest request) {
		String result = this.validationParameter(data, request, userService,"start", "pageSize", "starttime","endtime","useruuid");
		if (result == null) {
			JSONObject json = JsonUtils.converToJson(data);
			Map<String, Object> parameters = MapUtil.getMap();
			if (!StringUtils.isBlank(json.getString("starttime"))) {
				parameters.put(":starttime", json.getString("starttime"));
			}
			if (!StringUtils.isBlank(json.getString("endtime"))) {
				parameters.put(":endtime", json.getString("endtime"));
			}
			String token = request.getHeader("token");
			if (token != null) {
				DecodedJWT jwt;
				try {
					jwt = JWT.decode(token);
					if (jwt != null) {
						JSONObject userInfo = JsonUtils.converToJson(jwt.getSubject());
						if (userInfo != null) {
							User adminUser = userService.findByUserid(userInfo.getString(Config.tokenSignAttr));
							if (adminUser != null && UserUtil.checkRoleDown(adminUser)) {
									parameters.put(":useruuid", adminUser.getUseruuid());
							}
							if(!StringUtils.isBlank(json.getString("useruuid"))){
								parameters.put(":useruuid", json.getString("useruuid"));
							}
							return ResultMessage.getSucceed(
									JsonUtils.excludes(this.rechargeService.finddownRechargeRecordCount(parameters, json.getInt("start"),
											json.getInt("pageSize")), new String[] { "platFormAccount","errorCodesForUseruuid","createtime","useruuid",
													"password","","wechatid","lastlogintime" ,"token","usertype" ,"userstatus","phonenum" }));
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		return result;
	}


}
